package interfaces

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"time"
)

//对接口进行实现
type Logger struct {
	StoragePath string
	Version     string
	zap         *zap.Logger
}

func (log *Logger) Error(msg string, field ...zapcore.Field) {
	//加载日志组件
	log.newLogger().Error(msg, field...)
}
func (log *Logger) Info(msg string, field ...zapcore.Field) {
	//加载日志组件
	log.newLogger().Info(msg, field...)
}
func (log *Logger) Debug(msg string, field ...zapcore.Field) {
	//加载日志组件
	log.newLogger().Debug(msg, field...)
}
func (log *Logger) newLogger() *zap.Logger {
	//无需每天调用一条调用一次就可以
	if log.Version == "" || log.Version != time.Now().Format("2006-01-02") {
		//当没有的时候调用一次
		log.zap = zap.New(zapcore.NewCore(log.getEncoder(), log.getWriterLogger(), zap.DebugLevel))
		//更新版本
		log.Version = time.Now().Format("2006-01-02")
	}
	return log.zap
}

//修改zap原有的写入器已方便支持日志分割
func (log *Logger) getWriterLogger() zapcore.WriteSyncer {
	date := time.Now().Format("2006-01-02")
	writerLogger := lumberjack.Logger{
		Filename: log.StoragePath + "t_log_" + date + ".log",
	}
	return zapcore.AddSync(&writerLogger)
}

func (log *Logger) getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05")
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.TimeKey = "date"
	//输出json格式日志
	return zapcore.NewJSONEncoder(encoderConfig)
}
